package com.link.serve.tcp.process;

import com.link.serve.constants.ChannelAttrKey;
import com.link.serve.constants.RedisOperatorConstant;
import com.link.serve.kafka.producer.KafkaMessageProducer;
import com.link.serve.tcp.message.Message;
import com.link.serve.tcp.message.proto.PackHeader;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import static com.link.serve.type.IMCmdType.HEART_BEAT;
import static com.link.serve.utils.MessageUtils.buildResponseMessage;

/**
 * 心跳处理器
 * @Author: 杰
 * @Project :net-disk
 * @DateTime: 2024/7/2 14:30
 **/
@Slf4j
@Component
public class HeartbeatProcessor extends AbstractMessageProcessor<Message> {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private KafkaMessageProducer kafkaMessageProducer;

    @Override//客户端心跳的处理函数
    public void process(ChannelHandlerContext ctx, Message msg) throws ClassNotFoundException {
        PackHeader.Header header = msg.getHeader();
        // 获取用户相关属性
        AttributeKey<Long> userIdAttr = AttributeKey.valueOf(ChannelAttrKey.USER_ID);
        Long userId = ctx.channel().attr(userIdAttr).get();
        if (userId == null) {
            log.warn("接收到心跳消息，但未找到用户绑定信息，Channel ID: {}", ctx.channel().id().asLongText());
            return;
        }
        // 获取并更新心跳次数
        AttributeKey<Long> heartBeatAttr = AttributeKey.valueOf(ChannelAttrKey.HEARTBEAT_TIMES);
        Long heartbeatTimes = ctx.channel().attr(heartBeatAttr).get();
        ctx.channel().attr(heartBeatAttr).set(++heartbeatTimes);

        // 每 3 次心跳更新 Redis 在线状态
        if (heartbeatTimes % 3 == 0); //kafkaMessageProducer.sendRedisMessage(header, RedisOperatorConstant.HEARTBEAT, RedisOperatorConstant.HEARTBEAT);
        if(heartbeatTimes%20==0);//log.info("每20次心跳更新用户 {} 的在线状态, 心跳次数: {}", userId, heartbeatTimes);

        // 响应心跳消息
        Message response = buildResponseMessage(header.getAppId(), userId, "心跳响应成功", HEART_BEAT.code());
        ctx.writeAndFlush(response);
    }
}